﻿using Youz.Common.Helper;
using Youz.CreditRepay.BLL;
using Microsoft.AspNet.SignalR.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;

namespace Youz.CreditRepay.Manage
{
    public class ConnectSignalR
    {
        private static string signalRUrl = ConfigHelper.GetConfigString("SignalRUrl");
        private static IHubProxy HubProxy { get; set; }
        private static HubConnection Connection { get; set; }

        public static async void ConnectAsync()
        {
            if (Connection == null)
            {
                Connection = new HubConnection(signalRUrl);
                Connection.Closed += Connection_Closed;

                Cookie returnedCookie = await Task.Run(() => { return AuthenticateUser(); });
                if (returnedCookie != null)
                {
                    Connection.CookieContainer = new CookieContainer();
                    Connection.CookieContainer.Add(returnedCookie);
                    Core.WriteOperationLog("ConnectSignalR", "ConnectAsync", "登录成功 " + signalRUrl);
                }
                else
                {
                    Core.WriteOperationLog("ConnectSignalR", "ConnectAsync", "登录失败 " + signalRUrl);
                }

                HubProxy = Connection.CreateHubProxy("TickerHub");
            }

            try
            {
                if (Connection.State == ConnectionState.Disconnected)
                {
                    await Connection.Start();
                    Core.WriteOperationLog("ConnectSignalR", "ConnectAsync", "连接到 " + signalRUrl);
                }
            }
            catch (Exception ex)
            {
                Core.WriteErrorLog(ex);
                return;
            }
        }

        public static Cookie AuthenticateUser()
        {
            Cookie authCookie = null;
            var request = WebRequest.Create(signalRUrl.ToLower().Replace("signalr", "ajax/LoginHandler.ashx?type=SignalRLogin")) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = new CookieContainer();

            var authCredentials = "UserName=Signal&Password=" + CommonHelper.GetSHA512("Signal2016" + DateTime.Now.ToString("yyyyMMddHH"));
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(authCredentials);
            request.ContentLength = bytes.Length;
            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }

            using (var response = request.GetResponse() as HttpWebResponse)
            {
                authCookie = response.Cookies["Youz.CreditRepay.Login"];
            }

            return authCookie;
        }

        /// <summary>
        /// 重启交易，刷新客户端
        /// </summary>
        /// <param name="remark"></param>
        public static void Restart(string remark)
        {
            HubProxy.Invoke("Restart", "系统后台：" + remark);
        }

        /// <summary>
        /// 刷新用户资产
        /// </summary>
        /// <param name="memberAccount"></param>
        public static void RefreshAccount(string memberAccount)
        {
            HubProxy.Invoke("RefreshAccount", memberAccount);
        }

        /// <summary>
        /// 商品下市平仓
        /// </summary>
        /// <param name="goodsID"></param>
        public static void CloseContractByGoods(string goodsID)
        {
            HubProxy.Invoke("CloseContractByGoods", goodsID);
        }

        private static void Connection_Closed()
        {
            //Core.WriteOperationLog("ConnectSignalR", "ConnectAsync", "SignalR服务器连接已断开 " + signalRUrl);

            Connection.Start();
        }
    }
}